import { createApp } from 'vue'
import './style.css'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import axios from 'axios'
import router from './router'
import App from './App.vue'

// 配置axios
axios.defaults.baseURL = `${import.meta.env.VITE_API_URL}/api`
axios.defaults.timeout = 15000 // 增大超时时间，适合文件上传

// 添加请求拦截器
axios.interceptors.request.use(
  config => {
    const token = localStorage.getItem('access_token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    // 文件上传处理
    if (config.data instanceof FormData) {
      delete config.headers['Content-Type'];
    }
    
    return config
  },
  error => {
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

// 添加响应拦截器
axios.interceptors.response.use(
  response => {
    // 确保响应数据格式正确
    if (response.data === null || response.data === undefined) {
      console.warn('Empty response data received')
      response.data = {}
    }
    return response
  },
  async error => {
    const originalRequest = error.config
    
    // 如果是401错误且不是刷新token的请求
    if (error.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true
      
      try {
        const refreshToken = localStorage.getItem('refresh_token')
        if (!refreshToken) {
          throw new Error('No refresh token')
        }
        
        const response = await axios.post('/auth/token/refresh/', {
          refresh: refreshToken
        })
        
        const { access } = response.data
        localStorage.setItem('access_token', access)
        
        originalRequest.headers.Authorization = `Bearer ${access}`
        return axios(originalRequest)
      } catch (err) {
        // 清除所有认证信息
        localStorage.removeItem('access_token')
        localStorage.removeItem('refresh_token')
        localStorage.removeItem('username')
        router.push('/login')
        return Promise.reject(error)
      }
    }
    
    // 增强错误信息
    if (error.response) {
      console.error(`API Error (${error.response.status}):`, error.response.data)
    } else if (error.request) {
      console.error('No response received:', error.request)
    } else {
      console.error('Request setup error:', error.message)
    }
    
    return Promise.reject(error)
  }
)

const app = createApp(App)

// 注册所有图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
}

app.use(ElementPlus, {
  size: 'default',
  zIndex: 3000,
  config: {
    namespace: 'ep',
    button: {
      autoInsertSpace: true
    }
  }
})

// 检测系统主题并应用
const applyTheme = () => {
  const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
  document.documentElement.classList.toggle('dark', prefersDark)
  
  // 设置 Element Plus 的主题变量
  document.documentElement.style.setProperty('--el-bg-color', prefersDark ? '#1a1a1a' : '#ffffff')
  document.documentElement.style.setProperty('--el-bg-color-overlay', prefersDark ? '#242424' : '#ffffff')
}

// 初始应用主题
applyTheme()

// 监听系统主题变化
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', applyTheme)

app.use(router)

// 添加全局错误处理
app.config.errorHandler = (err, vm, info) => {
  console.error('Vue Error:', err, info)
  
  // 处理特定类型的错误
  if (err instanceof TypeError) {
    if (err.message.includes('is not a function')) {
      console.warn('数据类型错误，可能是API返回了意外的数据格式。详细信息:', err.message)
    }
  }
  
  // 防止错误传播
  return false
}

// 添加全局属性，用于检查数据类型
app.config.globalProperties.$isValidArray = (data) => {
  return Array.isArray(data) && data !== null
}

app.config.globalProperties.$safeArray = (data) => {
  return Array.isArray(data) ? data : []
}

app.mount('#app')
